package com.gsx.Config;

import com.gsx.handler.MyAuthenticationFailHandler;
import com.gsx.handler.MyAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;


@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private DataSource dataSource;
    //对安全的修改
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage("/log")
                .loginProcessingUrl("/login")
                //没写应该改成post请求
                /*.successForwardUrl("/admain/index")*/
                .successHandler(new MyAuthenticationSuccessHandler())
                .failureHandler(new MyAuthenticationFailHandler());
                /*.failureForwardUrl("/error")*/;//异步请求实现  再进入自己的处理


        http.authorizeRequests()
                .antMatchers("/admain/").permitAll()
                .antMatchers("/css/**","/images/**","/lib/**").permitAll()//放行所有的静态资源
                .antMatchers("/*").permitAll()//所用人都可以看的
                .antMatchers("/admain/**").hasAuthority("admain");

        http.logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/out");

        http.rememberMe()
                .tokenRepository(persistentTokenRepository())
                .tokenValiditySeconds(60)
                .userDetailsService(userDetailsService);



        //普通用户登录，无法同时使用，两个登录  需要寻找其他方法
        /*http.formLogin()
                .loginPage("/log")
                .loginProcessingUrl("/login")
                .successForwardUrl("/");*/

        http.csrf().disable();
    }
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Bean
    public PersistentTokenRepository persistentTokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository=new JdbcTokenRepositoryImpl();
        //设置数据源
        jdbcTokenRepository.setDataSource(dataSource);
        //自动建表 ，第一次使用时开启  第二次关闭 否则重复建表报错
        //jdbcTokenRepository.setCreateTableOnStartup(true);

        return jdbcTokenRepository;
    }
}
